﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SAP.Middleware.Connector;
using CM.DL.DALC.NC03;
using DECOR.BL.BE;

namespace DECOR.DL.DALC.NC03
{
    public class AlmacenDALC : IAlmacenDALC
    {
        private string _connId = string.Empty;

        public static AlmacenDALC Instance(string pConnId)
        {
            if (_instance == null)
            {
                lock (typeof(AlmacenDALC))
                {
                    if (_instance == null)
                    {
                        _instance = new AlmacenDALC(pConnId);
                    }
                }
            }
            _instance._connId = pConnId;
            return _instance;
        }
        private AlmacenDALC(string pConnId) { this._connId = pConnId; }
        private AlmacenDALC() { }
        private static volatile AlmacenDALC _instance = null;
        #region IAlmacenDALC Members

        public List<DECOR.BL.BE.GenericBE> listar(string pCodMaterial, string pCodCentro)
        {
            IRfcFunction function = null;
            DestConfig dc = new DestConfig();
            List<GenericBE> listaResult = new List<GenericBE>();
            GenericBE obj = null; 
            RfcDestination dest = null;
            string charSep = ParametroDALC.getParamValueStatic("charSep");
            try
            {
                dest = DALC.getDestination(out dc);
                function = dest.Repository.CreateFunction("ZWEB_LISTA_ALMACENES");
                function.SetValue("P_MATNR", pCodMaterial);
                function.SetValue("P_WERKS2", pCodCentro); //inicialmente se enviaba P_WERKS pero se cambio en SAP
                function.Invoke(dest);

                IRfcTable T001L = function.GetTable("T_T001L");

                foreach (IRfcStructure item in T001L)
                {
                    obj = new GenericBE();

                    obj.Codigo = item["LGORT"].GetString();
                    obj.Descripcion = (item["WERKS"].GetString() != string.Empty ? item["WERKS"].GetString() + charSep : "") + item["LGORT"].GetString() + charSep + item["LGOBE"].GetString();
                    listaResult.Add(obj);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //RfcDestinationManager.UnregisterDestinationConfiguration(dc);
            }
            return listaResult;
        }

        #endregion
    }
}
